from datetime import datetime
import random
import re

from flask import request, make_response, jsonify, current_app, session

from info import redis_store, constants, db
from info.lib.yuntongxun.sms import CCP
from info.models import User
from info.moduls.passport import passport_blu
from info.response_code import RET
from info.utils.captcha.captcha import captcha


@passport_blu.route('/image_code')
def get_img_code():
    """
    获取图片验证码
    1.获取从浏览器传来的uuid
    2.生成一张验证码图片
    3.以uuid为key,生成图片的实际值为value存入redis
    4.将图片返回浏览器
    """
    # 1.获取从浏览器传来的uuid
    code_id = request.args.get('code_id')

    # 2.生成一张验证码图片
    name, text, image = captcha.generate_captcha()

    # 3.以uuid为key,生成图片的实际值为value存入redis
    try:
        redis_store.setex('ImageCode_' + code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)
        current_app.logger.debug('图片验证码的内容为%s' % text)
    except Exception as e:
        current_app.logger.error(e)
        return make_response(jsonify(errno=RET.DATAERR, errmsg='保存图片信息失败'))

    # 将图片返回浏览器
    res = make_response(image)
    res.headers['Content-Type'] = 'image/jpg'
    return res


@passport_blu.route('/sms_code', methods=['POST'])
def send_message():
    """发送短信"""
    #  1.获取浏览器传来的mobile手机号,image_code用户输入的验证码,image_code_id验证码uuid
    param_dict = request.json
    mobile = param_dict.get('mobile')
    image_code = param_dict.get('image_code')
    image_code_id = param_dict.get('image_code_id')

    if not all([mobile, image_code, image_code_id]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不正确')

    #  2.根据image_code_id从redis中取出text,与image_code对比
    try:
        text = redis_store.get('ImageCode_' + image_code_id)
        # print(text)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据系统故障')

    if not text:
        return jsonify(errno=RET.NODATA, errmsg='图片已过期')

    if text.upper() != image_code.upper():
        return jsonify(errno=RET.DATAERR, errmsg='验证码输入错误')

    # 校验手机号码是否正确
    if not re.match('^1[356789][0-9]{9}$',mobile):
        return jsonify(errno=RET.DATAERR, errmsg='手机号码不存在')
    # 校验手机是否已经被注册
    try:
        user = User.query.filter_by(mobile=mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据系统故障')

    if user:
        return jsonify(errno=RET.DATAEXIST, errmsg='手机号已经被注册')

    #  3.通过则调用第三方短信工具,给用户发送短信,将短信内容存储
    # 生成短信验证码
    sms_code_str = '%06d' % random.randint(0,999999)
    current_app.logger.debug('短信验证码的内容为%s' % sms_code_str)
    # result = CCP().send_template_sms(mobile, [sms_code_str, constants.SMS_CODE_REDIS_EXPIRES / 60], 1)
    # if result != 0:
    #     return jsonify(errno=RET.THIRDERR, errmsg="发送验证码失败")

    # 将短信内容存储
    try:
        redis_store.setex('SMS_' + mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code_str)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据系统故障')
    return jsonify(errno=RET.OK, errmsg='验证码已经发送')


@passport_blu.route('/register', methods=['POST'])
def register():
    # 取到用户短信内容,与数据库短信内容对比
    param_dict = request.json
    mobile = param_dict.get('mobile')
    sms_code = param_dict.get('smscode')
    password = param_dict.get('password')

    if not all([mobile, sms_code, password]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不正确')
    try:
        sms = redis_store.get('SMS_' + mobile)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据系统故障')

    if not sms:
        return jsonify(errno=RET.NODATA, errmsg='短信验证码已过期')

    if sms.upper() != sms_code.upper():
        return jsonify(errno=RET.DATAERR, errmsg='短信验证码输入错误')

    # 删除短信验证码
    try:
        redis_store.delete('SMS_' + mobile)
    except Exception as e:
        current_app.logger.error(e)

    # 初始化user模型并添加到数据库
    user = User()
    user.mobile = mobile
    user.nick_name = mobile
    user.password = password

    # 通过则注册成功,设定初始账号密码
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DATAERR, errmsg="数据保存错误")

    # 5. session中保存用户登录状态
    session["user_id"] = user.id
    session["nick_name"] = user.nick_name
    session["mobile"] = user.mobile

    # 6. 返回注册结果
    return jsonify(errno=RET.OK, errmsg="OK")


@passport_blu.route('/login', methods=['POST'])
def login():
    # 接收参数
    param_dict = request.json
    mobile = param_dict.get('mobile')
    password = param_dict.get('password')

    # 对参数进行校验
    if not all([mobile,password]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数不全')

    try:
        user = User.query.filter(User.mobile==mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询失败')
    if not user:
        return jsonify(errno=RET.USERERR, errmsg='用户不存在')

    if not user.check_passowrd(password):
        return jsonify(errno=RET.PWDERR, errmsg='密码错误')


    # 保存用户登录状态和最后登录时间
    session['user_id'] = user.id
    session['nick_name'] = user.nick_name
    session['is_admin'] = user.is_admin
    session['mobile'] = user.mobile

    try:
        user.last_login = datetime.now()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DATAERR, errmsg="数据保存错误")

    # 返回登录信息
    return jsonify(errno=RET.OK, errmsg='OK')
